<?php
require_lib('common.function');
define('IN_OS', true);
require_lang('doctors');
class doctors{
    private $ctx;
    private $doctor;
    private $phone_time = 120;
    private $phone_multiple = 5;
    function __construct() {
        $this->ctx = $GLOBALS['context'];
        $this->doctor = load_model('doctor');
    }

    //检查是否登录
    private function  is_login() {
        $doctor_user_name = $this->ctx->get_session('doctor_user_name', true);
        if (!$doctor_user_name) {
            return true;
        } else {
            $doctor = $this->doctor->GetDoctorByUserName($doctor_user_name);
            if($doctor ) {
                $app_status = $doctor['AppStatus'];
                if($app_status != 4) {
                    switch($app_status) {
                        case 0:
                            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_first')),false);
                            break;
                        case 1:
                            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_first')),false);
                            break;
                        case 2:
                            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_md')),false);
                            break;
                        case 3:
                            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_last')),false);
                            break;
                    }
                }else {
                    $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/myInfo')),false);
                }
            }else {
                $this->ctx->redirect(get_redirect_url(get_app_url('/')),false);
            }
        }
    }
    //医生登录后首页
    function do_index(array & $request, array & $response, array & $app) {
        $username = $this->ctx->get_session('doctor_user_name',true);
        if(!$username) {
            $this->ctx->redirect('/',false);
        }else {
            $current_app_id = $this->ctx->get_session('current_apply_id', true);
            $res  = $this->doctor->GetDoctorByUserName($username);
            if($res && $res['AppStatus'] == 0 ) {
                $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_first')),false);
            }else if($res && $res['AppStatus'] ==1) {
                if($current_app_id) {
                    $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_first')),false);
                }
                $response['admin_message'] = lang('please_finish_you_apply');
            }else if($res && $res['AppStatus'] == 2) {
                if($current_app_id) {
                    $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_last')),false);
                }
                $response['admin_message'] = lang('please_finish_you_apply');
            }else if($res && $res['AppStatus'] == 3) {
                $response['admin_message'] = lang('please_wait_us_to_check_you_apply');
            }
        }
    }
    function owner_clinic(array & $request, array & $response, array & $app) {
        $username = $this->ctx->get_session('doctor_user_name',true);
        $roles = $this->ctx->get_session('DoctorRoles', true);
        if(!$username) {
            $this->ctx->redirect('/',false);
        }else {
            if(in_array(1, $roles)) {
                $request['doctor_user_name'] = $username;
            }else if(in_array(2,$roles) || in_array(3, $roles) || in_array(4,$roles)) {
                $request['is_expert'] = true;
                $userAssistants = load_model('doctorAssistant')->GetAssistantByDoctorUserName($username, true);
                if($userAssistants) {
                    $request['doctor_user_name'] = array();
                    foreach($userAssistants as $assistant) {
                        $request['doctor_user_name'] = $assistant['AssistantUserName'];
                    }
                }else {
                    $response['orders'] = array();
                }
            }
            load_model('patientRegistration')->GetRegistrationPageByDoctorId($request, $response);
            $rows = $response['get_page_row'];
            if($rows) {
                $response['current_order'] = $rows[0];
                $registration_id =  $response['current_order']['RegistrationId'];
                $response['order_detail'] = load_model('RegistrationDetail')->GetRegistrationDetailByRegistrationId($registration_id);
            }
        }
    }


    //医生登录
    function login(array & $request, array & $response, array & $app) {
        $this->is_login();
    }
    function do_login(array & $request, array & $response, array & $app) {
        $user_name = isset($request['user_name']) ? base64_decode( $request['user_name']) : '';
        $pwd = isset($request['password']) ? base64_decode($request['password']) : '';
        if(!$user_name) {
            return $response['data'] = array('code'=>0, 'msg'=>lang('user_name_not_allow_empty'));
        }
        if(!$pwd) {
            return $response['data'] = array('code'=>2, 'msg'=>lang('password_not_allow_empty'));
        }
        $user = $this->doctor->GetDoctorByUserName($user_name);
        if($user) {
            $res = $this->doctor->GetDoctorByUserNameAndPassword($user_name, md5($pwd));
            if($res) {
                $this->ctx->set_session('doctor_user_name', $user_name, true);
                $roles = load_model('doctorRole')->GetApprovedRoleByDoctorUserName($user_name);
                if($roles) {
                    $role_ids = array();
                    foreach($roles as $role) {
                        $role_ids[] = $role['RoleId'];
                    }
                    $this->ctx->set_session('DoctorRoles', $role_ids, true);
                }
                return $response['data'] = array('code'=>1, 'msg'=>lang('login').lang('success'));
            }else {
                return $response['data'] = array('code'=>3, 'msg'=>lang('password_is_error'));
            }
        }else {
            return $response['data'] = array('code'=>2, 'msg'=>lang('user_not_exist'));
        }
    }
    //医生注册
    function register(array & $request, array & $response, array & $app) {
        $this->is_login();
        //$this->doctor->add_doctor($this->request, $this->response);
    }
    function do_register(array & $request, array & $response, array & $app) {
        $user_name = isset($request['user_name']) ? base64_decode($request['user_name']) : '';
        $phone = isset($request['phone']) ? base64_decode($request['phone']) : '';
        $pwd = isset($request['password']) ? base64_decode($request['password']) : '';
        $cpwd = isset($request['repassword']) ? base64_decode($request['repassword']) : '';
        //手机验证码
        $check_code = isset($request['check_code']) ? base64_decode($request['check_code']) : '';
        //短信验证码 //待准备
        $checknumber = isset($request['checknumber']) ? strtolower($request['checknumber']) : '';

        //$validimg = $this->ctx->get_session('validimg_doctor_reg', true);
        //$validimg = strtolower($validimg);

        //输入的 验证码 是不是正确,防刷屏的
        /*
        if ($checknumber != $validimg || empty($validimg) || empty($checknumber)) {
            return $response['data'] = array('msg' => lang(''), 'code' => -102);
        }
        */


        if (empty($phone) || !preg_match("/^(((1[1-9]{1})|(1[1-9]{1})|(1[1-9]{1}))+\d{9})$/", $phone)) {
            return $response['data'] = array('msg' => lang('the_format_of_the_mobile_is_error'), 'code' => 4);
        }

        /*//验证手机验证码 start*/
        /*
            if(!$check_code) {
                return $response['data'] = array('msg' =>lang('checked_code_is_empty'), 'code' => 6);
            }
            $check_tel_code = $this->ctx->get_session('phone_'.$phone, true);
            $check_time = $this->ctx->get_session('phone_'.$phone.'_time', true);
            if(!(isset($check_tel_code) && isset($check_time) && $check_time-time() <= $this->phone_time * $this->phone_multiple) ) {
                return $response['data'] = array('msg' => lang('checked_code_is_gone'), 'code' => 7);
            }
            if($check_tel_code != $check_code) {
                return $response['data'] = array('msg' => lang('checked_code_is_error'), 'code' => 8);
            }
        */
        /*//验证手机验证码 end*/
        if($pwd !== $cpwd) {
            return $response['data'] = array('code'=>2, 'msg'=>lang('not_the_same_password'));
        }
        if($user_name) {
            $usernameres = $this->doctor->GetDoctorByUserName($user_name);
            if($usernameres) {
                return $response['data'] = array('code'=>0, 'msg'=>lang('user_name_is_exist'));
            }
        }
        if($phone) {
            $res = $this->doctor->GetDoctorByDoctorId($phone);
            if($res) {
                return $response['data'] = array('code'=>3, 'msg'=>lang('phone_is_exist'));
            }
        }
        $insert = array('UserName'=>$user_name, 'DoctorId'=>$phone , 'Password'=>md5($pwd));
        $r = $this->doctor->CreateDoctor($insert);
        //注册是否成功
        if (!$r) {
            return $response['data'] = array('msg' =>lang('failure'), 'code' => 5);
        }
        $this->ctx->set_session('doctor_user_name', $user_name, true);
        return $response['data'] = array('msg' => lang('success'), 'code' => 1);
    }
    function user_logout(array & $request, array & $response, array & $app) {
        /*
        session_destroy();
        session_unset();
        $domain = '';
        setcookie('doctor_user_name', '', -86400, '/', $domain);
        $response['data'] = array('code' => 0, 'msg' => '退出成功');
        */
        session_destroy();
        session_unset();
        clean_session('doctor_user_name', true);
        header('Location: /');
    }
    function user_name_check(array & $request, array & $response, array & $app) {
        $user_name = isset($request['user_name']) ? $request['user_name'] : '';
        $result = $this->doctor->GetDoctorByUserName($user_name);
        if($result) {
            $response['data'] = array('code'=>0, 'msg'=>lang('user_name_is_exist'));
        }else{
            $response['data'] = array('code'=>1, 'msg'=>lang('user_name_is_not_exists'));
        }
    }
    function user_phone_check(array & $request, array & $response, array & $app) {
        $phone = isset($request['phone']) ? $request['phone'] : '';
        $result = $this->doctor->GetDoctorByDoctorId($phone);
        if($result) {
            $response['data'] = array('code'=>0, 'msg'=>lang('phone_is_registered'));
        }else{
            $response['data'] = array('code'=>1, 'msg'=>lang('phone_is_not_exists'));
        }
    }
    function send_check_code(array & $request, array & $response) {
        if(isset($request['phone']) && $request['phone']){
            $phone = $request['phone'];
            $num = $this->doctor->GetDoctorByDoctorId($phone);
            if(count($num) == 0) {
                if($this->ctx->get_session('phone_'.$phone, true)) {
                    $prv_send_time = $this->ctx->get_session('phone_'.$phone.'_time', true);
                    if($prv_send_time- time() >= $this->phone_time * $this->phone_multiple) {
                        $domain = $this->ctx->shop_conf->get('shop_domain');
                        setcookie('phone_'.$phone.'_time', '', -86400, '/', $domain);
                        return $response['data'] = array('code'=>'-1');
                    }
                }
                /*
                $code = random(6, true);
                $this->ctx->set_session('phone_'.$phone, $code, true);
                $this->ctx->set_session('phone_'.$phone.'_time', time()+$this->phone_time*$this->phone_multiple, true);

                $msg = '51天使网提醒您：您注册的手机号码的验证码为：'.$code.'，请在注册页面填写验证码完成注册。【51天使网】';
                $responseXML = load_model('sms/sms')->sendSMS($phone,iconv('UTF-8','GB2312',$msg));
                $this->ctx->log_error('phone:'.$phone. '--->返回信息：'.$responseXML.'--->msg:'.$msg);
                $responseXML  = 1 ;
                if((int)$responseXML >= 0) {
                    $code = 1;
                } else {
                    $code = 0 ;
                }
                */
                return $response['data'] = array('code'=>isset($code) ? $code : 0, 'time'=>$this->phone_time);
            } else {
                return $response['data'] = array('code'=>'2', 'msg'=>lang('phone_is_registered'));
            }
        } else {
            return $response['data'] = array('code'=>'-1');
        }
    }
    function upload_img(array & $request, array & $response, array & $app) {
        $upload_name = isset($request['upload_name']) ?$request['upload_name'] :'';
        $img_dir = 'doctors';
        $file_name = $this->ctx->get_session('doctor_user_name', true).'_head';
        if(isset($file_name) && $file_name) {
            $is_mark  = isset($request['is_mark'])?$request['is_mark']:0;
            $response['data'] = load_model('image')->upload_image( $_FILES[$upload_name], $img_dir, $file_name ,$is_mark, 'DoctorProofImage', $upload_name);
            return  $response['data'];
        }else {
            return $response['data'] = array('code'=>1,'msg'=>'error');
        }
    }
    //显示图片
    function show_img(array & $request) {
        $this->doctor->show_img($request);
    }
    //医生个人信息页
    function myInfo(array & $request, array & $response, array & $app) {
        //$this->is_login();
        $username = $this->ctx->get_session('doctor_user_name',true);
        $response['doctor'] = $this->doctor->GetDoctorByUserName($username);
    }
    //添加个人信息
    function add_my_info(array & $request, array & $response, array & $app) {
        $update = array();
        $update['Name'] = isset($request['UserName']) && $request['UserName'] ? $request['UserName'] : '';
        $update['PersonId'] = isset($request['PersonId']) && $request['PersonId'] ? $request['PersonId'] : '';
        $update['Birthday'] = isset($request['Birthday']) && $request['Birthday'] ? $request['Birthday'] : '';
        $update['EducationLevel'] = isset($request['EducationLevel']) && $request['EducationLevel'] ? $request['EducationLevel'] : '';
        $update['GraduateUniversity'] = isset($request['GraduateUniversity']) && $request['GraduateUniversity'] ? $request['GraduateUniversity'] : '';
        $update['ExpertiseAreas'] = isset($request['ExpertiseAreas']) && $request['ExpertiseAreas'] ? $request['ExpertiseAreas'] : '';
        $update['HeadImageId'] = isset($request['HeadImageId']) && $request['HeadImageId'] ? $request['HeadImageId'] : '';
        $update['Intro'] = isset($request['Intro']) && $request['Intro'] ? $request['Intro'] : '';
        $update['Tutor'] = isset($request['Tutor']) && $request['Tutor'] ? $request['Tutor'] : '';
        $flag = $this->doctor->ModifyDoctor($update);
        if($flag) {
            $response['data'] = array('code'=>0,'msg'=>'success');
        }else {
            $response['data'] = array('code'=>1,'msg'=>'failure');
        }
    }
    //个人账户信息
    function account(array & $request, array & $response, array & $app) {

    }
    //候诊大厅
    function wait_hall(array & $request, array & $response, array & $app){

    }
    //我的同事
    function assistant(array & $request, array & $response, array & $app) {
        $username = $this->ctx->get_session('doctor_user_name', true);
        if($username) {
            //$doctor = $this->doctor->GetDoctorByUserName($username);
            //print_r($_SESSION);

        }else {
            $this->ctx->redirect('/',false);
        }

    }
    //我的诊室
    function clinic(array & $request, array & $response, array & $app) {

    }
    //我当前的咨询
    function consult(array & $request, array & $response, array & $app) {

    }

    function app_first(array & $request, array & $response, array & $app) {
        $doctor_user_name = $this->ctx->get_session('doctor_user_name', true);

        $apply = load_model('doctorApply')->GetDoctorApplyByUserNameAndCheckStatus($doctor_user_name, 0);
        if($apply) {
            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/')),false);
        }

        $res = $this->doctor->GetDoctorByUserName($doctor_user_name);
        $response['doctors'] = $res ? $res : array();
        $response['hospital'] =  load_model('hospital')->GetHospitals();
        $current_app_id = $this->ctx->get_session('current_apply_id', true);
        if($current_app_id) {
            $response['app_first'] = load_model('doctorApply')->GetCurrentApplyById($current_app_id);
        }
    }
    function do_app_first(array & $request, array & $response, array & $app) {
        $username = $this->ctx->get_session('doctor_user_name', true);
        $current_apply_id = $this->ctx->get_session('current_apply_id', true);
        if($current_apply_id) {
            $update = array(
                'CurrentDepartmentId'=>isset($request['hospital']) ?$request['hospital'] : '',
                'DepartmentId'=>isset($request['DepartmentId']) ?$request['DepartmentId'] : 1,
                'UserName'=>$username,
                'ApplyStatus'=>1,
            );
            load_model('doctorapply')->UpdateCurrentApply($update);
            $id = $current_apply_id;
        }else {
            $insert = array(
                'CurrentDepartmentId'=>isset($request['hospital']) ?$request['hospital'] : '',
                'DepartmentId'=>isset($request['DepartmentId']) ?$request['DepartmentId'] : 1,
                'UserName'=>$username,
                'ApplyStatus'=>1,
            );
            $id = load_model('doctorApply')->AddApply($insert);
        }
        $applied_app = load_model('doctorApply')->GetDoctorApplyByUserNameAndCheckStatus($username, 3);
        if(count($applied_app) ==0) {
            $update = array(
                'PersonId'=>isset($request['sign_id']) ?$request['sign_id'] : '',
                'Birthday'=>isset($request['birthday']) ?$request['birthday'] : '',
                'HeadImageId'=>isset($request['user_head_img']) ?$request['user_head_img'] : '',
                'AppStatus'=>1,
            );
            $this->doctor->ModifyDoctor($update);
        }
        $this->ctx->set_session('current_apply_id', $id, true);
        if($id) {
            return $response['data'] = array('code'=>0,'msg'=>'success');
        }else {
            return $response['data'] = array('code'=>1,'msg'=>'failure');
        }
    }
    function app_md(array & $request, array & $response, array & $app) {
        $res = load_model('doctorApply')->GetCurrentApplyById();
//        print_r($res);
//        exit;
        $response['doctors'] = $res ? $res : array();
        if($res) {
            $app_status = $res['ApplyStatus'];
            if($app_status != 4) {
                switch($app_status) {
                    case 0:
                        $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_first')),false);
                        break;
                }
            }
        }else {
            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/')),false);
        }
    }
    function do_app_md(array & $request, array & $response, array & $app) {
        $username = $this->ctx->get_session('doctor_user_name', true);
        $update = array(
            'ProfessionImage'=>isset($request['profession_img']) ?$request['profession_img'] : 0,
            'QualificationImage'=>isset($request['qualifications_img']) ?$request['qualifications_img'] : 0,
            //'proof_img'=>isset($request['proof_img']) ?$request['proof_img'] : 0,
            'ApplyStatus'=>2,
        );
        $current_apply_id = $this->ctx->get_session('current_apply_id', true);
        if($current_apply_id) {
            $res = load_model('doctorApply')->UpdateCurrentApply($update);
            if($res) {
                $applied_app = load_model('doctorApply')->GetDoctorApplyByUserNameAndCheckStatus($username, 3);
                if(count($applied_app) ==0) {
                    $update = array(
                        'AppStatus'=>2,
                    );
                    $this->doctor->ModifyDoctor($update);
                }
                return $response['data'] = array('code'=>0,'msg'=>'success');
            }else {
                return $response['data'] = array('code'=>1,'msg'=>'failure');
            }
        }else {
            return $response['data'] = array('code'=>1,'msg'=>'failure');
        }
    }
    function app_last(array & $request, array & $response, array & $app) {
        $doctor_user_name = $this->ctx->get_session('doctor_user_name', true);
        $res = load_model('doctorApply')->GetCurrentApplyById();
        $response['doctors'] = $res ? $res : array();
        if($res) {
            $app_status = $res['ApplyStatus'];
            if($app_status != 4) {
                switch($app_status) {
                    case 0:
                        $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_first')),false);
                        break;
                    case 1:
                        $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_md')),false);
                        break;
                }
            }
        }else {
            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/')),false);
        }
    }
    function do_app_last(array & $request, array & $response, array & $app) {
        $username = $this->ctx->get_session('doctor_user_name', true);
        $role = isset($request['role']) ? $request['role'] : '';
        $server_type = isset($request['server_type']) ? $request['server_type'] : '';

        $roles = explode('_', trim($role, '_'));
        if(empty($roles)) {
            return $response['data'] = array('code'=>2,'msg'=>'select_the_consult_type');
        }
        $server_types = explode('_', trim($server_type, '_'));
        if(empty($server_types)) {
            return $response['data'] = array('code'=>3,'msg'=>'select_the_server_type');
        }
        $update = array(
            'ConsultType'=>implode(',', $roles),
            'ServerType'=>implode(',', $server_types),
            'ApplyStatus'=>3,
            'ApplyDate'=>date('Y-m-d'),
        );
        $current_apply_id = $this->ctx->get_session('current_apply_id', true);
        if($current_apply_id) {
            $res = load_model('doctorApply')->UpdateCurrentApply($update);
            if($res) {
                $applied_app = load_model('doctorApply')->GetDoctorApplyByUserNameAndCheckStatus($username, 3);
                if(count($applied_app) ==0) {
                    $update = array(
                        'AppStatus'=>3,
                    );
                    $this->doctor->ModifyDoctor($update);
                }
                return $response['data'] = array('code'=>0,'msg'=>'success');
            }else {
                return $response['data'] = array('code'=>1,'msg'=>'failure');
            }
        }else {
            return $response['data'] = array('code'=>1,'msg'=>'failure');
        }
    }
    //医生资格重新申请
    function app_confirm(array & $request, array & $response, array & $app){
        $username = $this->ctx->get_session('doctor_user_name', true);
        $current_apply_id = $this->ctx->get_session('current_apply_id', true);
        $response['apply'] = $res =  load_model('doctorApply')->GetCurrentApplyById();
        if($res) {
            $app_status = $res['ApplyStatus'];
            if($app_status != 4) {
                switch($app_status) {
                    case 0:
                        $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_first')),false);
                        break;
                    case 1:
                        $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_md')),false);
                        break;
                    case 2:
                        $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_last')),false);
                        break;
                }
            }
        }else {
            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/')),false);
        }
    }
    function do_app_confirm() {
        $username = $this->ctx->get_session('doctor_user_name', true);
        if($username) {
            clean_session('current_apply_id', true);
            $this->ctx->redirect(get_redirect_url(get_app_url('center/doctors/app_first')),false);
        }
    }
    //医生预检病例
    function preflight_case(array & $request, array & $response, array & $app) {

    }

}
